import { Message } from 'element-ui'
export default {
  // 获取网址的参数
  getUrlParms(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    const path = window.location.search.substr(1)
    const hash = window.location.hash
    const index = hash.lastIndexOf('?')
    let str
    if (path) {
      str = path
    } else {
      str = hash.substring(index + 1, hash.length)
    }
    const r = str.match(reg)
    // let reg_chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g')  // 检测中文
    if (r !== null) {
      return decodeURI(r[2])
      // unescape(r[2]) encodeURI()把中文转义
    }
    return null
  },
  // HTML转义
  HTMLEncode(html) {
    var temp = document.createElement('div');
    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html)
    var output = temp.innerHTML
    temp = null
    return output
  },
  // HTML 反转义
  HTMLDecode(text) {
    var temp = document.createElement('div')
    temp.innerHTML = text
    var output = temp.innerText || temp.textContent
    temp = null
    return output
  },
  valid(rules, form, showClose = true) { // 表单验证
    var rules = rules
    var form = form
    for (var key in rules) {
      for (var i = 0; i < rules[key].length; i++) {
        if (rules[key][i].required) {
          if (form[key] === '') {
            Message({
              showClose: showClose,
              message: rules[key][i].message,
              type: 'error'
            })
            return false
          }
        } else if (rules[key][i].pattern) {
          if (!rules[key][i].pattern.test(form[key])) {
            Message({
              showClose: showClose,
              message: rules[key][i].message,
              type: 'error'
            })
            return false
          }
        } else if (rules[key][i].minLength) {
          if (form[key].length < rules[key][i].minLength) {
            Message({
              showClose: showClose,
              message: rules[key][i].message,
              type: 'error'
            })
            return false
          }
        } else if (rules[key][i].maxLength) {
          if (form[key].length > rules[key][i].maxLength) {
            Message({
              showClose: showClose,
              message: rules[key][i].message,
              type: 'error'
            })
            return false
          }
        } else if (rules[key][i].validator) {
          if (typeof rules[key][i].validator === 'function') {
            if (!rules[key][i].validator()) {
              return false
            }
          }
        }
      }
    }
    return true
  },
  getLocal(key) {
    var val = window.localStorage.getItem(key)
    if (val === 'undefined') {
      return ''
    }
    return window.localStorage.getItem(key)
  },
  setLocal(key, val) {
    window.localStorage.setItem(key, val)
    return true
  },
  getSession(key) {
    var val = window.sessionStorage.getItem(key)
    if (val === 'undefined') {
      return ''
    }
    return window.sessionStorage.getItem(key)
  },
  setSession(key, val) {
    window.sessionStorage.setItem(key, val)
    return true
  },
  /** 对象深拷贝 */
  OParse(obj) {
    try {
      return JSON.parse(JSON.stringify(obj))
    } catch (e) {
      return {}
    }
  },
  deepCopy(obj) {
    // 只拷贝对象
    if (typeof obj !== 'object') return
    // 根据obj的类型判断是新建一个数组还是一个对象
    var newObj = obj instanceof Array ? [] : {}
    for (var key in obj) {
      // 遍历obj,并且判断是obj的属性才拷贝
      if (obj.hasOwnProperty(key)) {
        // 判断属性值的类型，如果是对象递归调用深拷贝
        newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key]
      }
    }
    return newObj
  },
  objAssi(obj1, obj2) {
    for (var key in obj1) {
      for (var key2 in obj2) {
        key2 === key && (obj1[key] = obj2[key])
      }
    }
    return obj1
  },
  upload(options, request, callBack) {
    const file = options.file // 获取文件对象
    const isLt2M = file.size / 1024 / 1024 < 2 // 判断图片大小
    var isJPG = file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/JPG'
    if (!isJPG) { // 判断图片类型
      Message({
        showClose: true,
        message: '上传产品图片只能是 JPG/PNG/JPEG 格式!',
        type: 'error'
      })
      return false
    } else if (!isLt2M) {
      Message({
        showClose: true,
        message: '上传产品图片大小不能超过 2MB!',
        type: 'error'
      })
      return false
    }
    // 创建一个HTML5的FileReader对象
    var reader = new FileReader()
    if (file) {
      reader.readAsDataURL(file)
    }
    reader.onload = e => {
      request({ path: reader.result }).then(res => {
        if (res.stateCode === 1) {
          callBack(res.data)
        } else {
          this.$message({
            showClose: true,
            message: '上传失败',
            type: 'error'
          })
        }
      }).catch(res => {
        Message({
          showClose: true,
          message: '上传失败',
          type: 'error'
        })
      })
    }
  }
}

